//
//  ISDatabase.m
//  LC
//
//  Created by admin on 2017/6/27.
//
//

#import "LCBaseDatabase.h"
#import "sys/xattr.h"

@implementation LCBaseDatabase

IMPLEMENTATION_SINGLETON(LCBaseDatabase)

- (instancetype)init
{
    self = [super init];
    if (self) {
        _db = [LCBaseDatabase databaseQueueWithPath:[self dbPathSqliteName:kDbSqlName]];
    }
    return self;
}

///读取数据库版本
-(void)setDbVersion:(NSInteger)dbVersion{
    [[NSUserDefaults standardUserDefaults] setInteger:dbVersion forKey:@"DBVERSION"];
}

-(NSInteger)dbVersion{
    return [[NSUserDefaults standardUserDefaults] integerForKey:@"DBVERSION"];
}

/**
 *  创建文件夹和 获取数据库路径
 *
 *  @return 路径
 */
-(NSString *)dbPathSqliteName:(NSString *)sqliteName{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *fileString = [self libraryPathSearchPath];//返回目录 目录设置方法 libraryPathSearchPath
    BOOL success = [fileManager fileExistsAtPath:fileString];//判断一个给的路径是否为文件夹
    if (!success) {
        success = [fileManager createDirectoryAtPath:fileString withIntermediateDirectories:NO attributes:nil error:nil];
        if (success) {
            [self addSkipBackupAttributeToPath:fileString];
            NSLog(@"创建目录成功!");
        }else{
            NSLog(@"创建目录失败!");
        }
    }else {
//        NSLog(@"数据库目录已存在 不需要创建");
    }
    
    NSString *dbPath = [self getPath:fileString sqliteName:sqliteName];//拼接上数据库文件名
//    success = [fileManager fileExistsAtPath:dbPath];//判断一个给定路径是否为文件夹
//        if (success) {
////            NSLog(@"数据库文件存在!");
//        }else{
////            NSLog(@"数据库文件不存在!");
//        }
    return dbPath;
}
//对文件夹的path使用这两个方法中的任意一个，就可以使该目录和该目录包含的所有文件和文件夹不被icloud和itunes同步了！
- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    const char* filePath = [[URL path] fileSystemRepresentation];
    
    const char* attrName = "com.apple.MobileBackup";
    u_int8_t attrValue = 1;
    
    int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
    return result == 0;
}
- (void)addSkipBackupAttributeToPath:(NSString*)path {
    u_int8_t b = 1;
    setxattr([path fileSystemRepresentation], "com.apple.MobileBackup", &b, 1, 0, 0);
}


- (NSString *)conversionLibraryImagePathOne:(NSString *)imagePath {
    NSString *libraryString = @"Library";
    NSRange range = [imagePath rangeOfString:libraryString];
    if (range.location != NSNotFound) {
        NSUInteger len = range.location+[libraryString length]+1;
        if (len > [imagePath length]) {
            return nil;
        }
        NSString *subString = [imagePath substringFromIndex:len];
        NSArray *libraryPaths = kLibraryPath;
        NSString *libraryPath = [libraryPaths objectAtIndex:0];
        NSString *lbFilePath = [libraryPath stringByAppendingPathComponent:subString];
        return lbFilePath;
    }
    else {
        return nil;
    }
}
/**
 *  获取  拼有Application Support 文件夹的Document沙盒路径
 *
 *  @return 返回拼有Application Support 文件夹的Document沙盒路径
 */
- (NSString *)libraryPathSearchPath {
    NSArray *paths = kDocumentPath;
    NSString *cachesPath = [paths objectAtIndex:0];
    NSString *fileDirectory = [cachesPath stringByAppendingPathComponent:kApplicationSupportName];
    return fileDirectory;
}
/**
 *  拼接沙盒和文件 dbPath
 *
 *  @param libraryPath 沙盒路径
 *  @param sqliteName     文件名字
 *
 *  @return 返回拼接好的沙盒和文件路径
 */
- (NSString *)getPath:(NSString *)libraryPath sqliteName:(NSString *)sqliteName {
    return [libraryPath stringByAppendingPathComponent:sqliteName];
}

#pragma mark 日期时间相关
- (NSString *)dateFormatter1970ForTimestamp:(unsigned int)chatTimestamp formatterString:(NSString *)formatterString {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:formatterString];
    NSDate *modifyDate = [NSDate dateWithTimeIntervalSince1970:chatTimestamp];
    NSString *string = [formatter stringFromDate:modifyDate];
    return string;
}

//二、NSFileManager常用的文件管理操作
//1、创建目录  createDirectoryAtPath：
//2、创建文件  createFileAtPath：
//3、删除某个文件  removeItemAtPath:
//4、检查某个文件是否存在  fileExistsAtPath:
//5、检查文件是否可读 isReadableFileAtPath:
//是否可写：isWritableFileAtPath:
//6、取得文件属性  fileAttributesAtPath:
//改变文件属性changeAttributesAtPath:
//7、从path代表的文件中读取数据：contentsAtPath
//8、移动文件movePath:toPath:handler:
//9、复制文件copyPath:toPath:handler:
@end
